<template>
	<el-card>
		<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item>
				<el-date-picker
					v-model="createTM"
					type="daterange"
					range-separator="--"
					start-placeholder="创建时间(开始)"
					end-placeholder="创建时间(结束)"
					style="width: 250px"
				>
				</el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-input v-model="state.queryForm.username" placeholder="请输入用户名/姓名/手机号" clearable></el-input>
			</el-form-item>
			<!-- <el-form-item>
				<fast-select v-model="state.queryForm.orgTypeCode" dict-type="org_type" clearable placeholder="请选择机构类型"> </fast-select>
			</el-form-item> -->
			<el-form-item>
				<el-select v-model="state.queryForm.status" placeholder="请选择状态" clearable>
					<el-option label="启用" value="1"></el-option>
					<el-option label="禁用" value="0"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button @click="search()" type="primary" :icon="Search">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button :icon="Refresh" @click="resets">重置</el-button>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:user:disbale'" :icon="CircleClose" type="primary" @click="disableBatchHandle()">批量禁用</el-button>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:user:delete'" :icon="Delete" type="primary" @click="deleteBatchHandle()">批量删除</el-button>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:user:save'" :icon="Plus" type="primary" @click="addOrUpdateHandle()">新建</el-button>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:user:handleMove'" type="primary" @click="handleMove()">手动同步</el-button>
			</el-form-item>
		</el-form>
		<el-table v-loading="state.dataListLoading" :data="state.dataList" border style="width: 100%" @selection-change="selectionChangeHandle">
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column label="序号" type="index" width="60" align="center"> </el-table-column>
			<el-table-column prop="username" label="用户名" header-align="center" align="center"></el-table-column>
			<el-table-column prop="realName" label="姓名" header-align="center" align="center"></el-table-column>
			<el-table-column prop="orgName" label="所属机构" header-align="center" align="center"></el-table-column>
			<el-table-column prop="department" label="科室" header-align="center" align="center"></el-table-column>
			<el-table-column prop="status" label="状态">
				<template #default="scope">
					<el-switch
						:disabled="isDisabled('sys:user:switch')"
						:model-value="scope.row.status"
						:active-value="1"
						:inactive-value="0"
						@change="statusChange($event, scope.row)"
					></el-switch>
					<span style="margin-left: 10px">
						{{ scope.row.status === 1 ? '启用' : '禁用' }}
					</span>
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" header-align="center" align="center" width="120">
				<template #default="scope">
					{{ timeFmt(scope.row.createTime) }}
				</template>
			</el-table-column>
			<el-table-column prop="updateTime" label="修改时间" header-align="center" align="center" width="120">
				<template #default="scope">
					{{ timeFmt(scope.row.updateTime) }}
				</template>
			</el-table-column>
			<!-- <el-table-column prop="mobile" label="手机号" header-align="center" align="center"></el-table-column> -->
			<!-- <el-table-column prop="email" label="邮箱" header-align="center" align="center"></el-table-column> -->
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
				<template #default="scope">
					<el-button v-auth="'sys:user:details'" type="primary" link @click="addOrUpdateHandle(scope.row.id, 'details')">详情</el-button>
					<el-button v-auth="'sys:user:update'" type="primary" link @click="addOrUpdateHandle(scope.row.id, 'edit')">编辑</el-button>
					<el-button v-auth="'sys:user:reset'" type="primary" link @click="resetPassword(scope.row.id)">重置密码</el-button>
					<el-button v-auth="'sys:user:delete'" type="primary" link @click="deleteBatchHandle(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.limit"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>

		<!-- 弹窗, 新增 / 修改 -->
		<add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update>
		<HandleMove ref="handleMoveRef"  @refreshDataList="getDataList"></HandleMove>
	</el-card>
</template>

<script setup lang="ts" name="SysUserIndex">
import { Delete, Edit, Search, Plus, CircleClose, Refresh } from '@element-plus/icons-vue'
import { useCrud } from '@/hooks/indexUser.ts'
import { reactive, ref } from 'vue'
import AddOrUpdate from './add-or-update.vue'
import { IHooksOptions } from '@/hooks/interface'
import timeFormater from 'time-formater'
import { ElMessage, ElMessageBox } from 'element-plus'
import { throttle } from '@/utils/tool'
import HandleMove from './handleMove.vue'
import { useUserApi, useUserSubmitApi, resetPasswordApi, SynsUserInfo } from '@/api/sys/user'
import store from '@/store'

const createTM = ref('')

const state: IHooksOptions = reactive({
	dataListUrl: '/sys/user/page',
	deleteUrl: '/sys/user',
	disableUrl: '/sys/user/disable',
	queryForm: {
		startTime: createTM.value ? timeFormater(createTM.value[0]).format('YYYY-MM-DD') : '',
		endTime: createTM.value ? timeFormater(createTM.value[1]).format('YYYY-MM-DD') : '',
		status: '',
		username: '',
		projectId: 1,
		orgId: JSON.parse(sessionStorage.getItem('userInfo')).orgId
	},
	dataListSelections: [],
	order: 'create_time',
	asc: false
})

const isDisabled = (name: string) => {
	return !store.userStore.authorityList.some((v: string) => v === name)
}

// const statusChange = (event, data) => {
// 	const dataForm = {
// 		id: '',
// 		username: '',
// 		realName: '',
// 		orgId: JSON.parse(sessionStorage.getItem('userInfo')).orgId,
// 		orgName: '',
// 		password: '888888',
// 		mobile: '',
// 		roleIdList: [] as any[],
// 		postIdList: [] as any[],
// 		status: event,
// 		remark: ''
// 	}
// 	let orgIda = JSON.parse(sessionStorage.getItem('userInfo')).orgId
// 	let param = data.id + '/' + orgIda
// 	useUserApi(param).then(res => {
// 		res.data.status = event
// 		Object.assign(dataForm, res.data)

// 		ElMessageBox.confirm(event ? '确定进行用户启用操作?' : '确定进行用户禁用操作?', '提示', {
// 			confirmButtonText: '确定',
// 			cancelButtonText: '取消',
// 			type: 'warning'
// 		})
// 			.then(() => {
// 				useUserSubmitApi(dataForm).then(() => {
// 					ElMessage.success({
// 						message: '操作成功',
// 						duration: 500,
// 						onClose: () => {
// 							getDataList()
// 						}
// 					})
// 				})
// 			})
// 			.catch(() => {
// 				data.status = event ? 0 : 1
// 			})
// 	})
// }
const statusChange = async (event, item) => {
	await ElMessageBox.confirm(event ? '确定进行用户启用操作?' : '确定进行用户禁用操作?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			return Promise.resolve()
		})
		.catch(() => {
			return Promise.reject()
		})
	const dataForm = {
		id: '',
		username: '',
		realName: '',
		orgId: JSON.parse(sessionStorage.getItem('userInfo')).orgId,
		orgName: '',
		password: '888888',
		mobile: '',
		roleIdList: [] as any[],
		postIdList: [] as any[],
		status: event,
		remark: ''
	}
	let orgIda = JSON.parse(sessionStorage.getItem('userInfo')).orgId
	let param = item.id + '/' + orgIda
	useUserApi(param).then(res => {
		res.data.status = event
		Object.assign(dataForm, res.data)
		useUserSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					getDataList()
				}
			})
		})
	})
}

const timeFmt = data => {
	return timeFormater(data).format('YYYY-MM-DD')
}

const search = () => {
	state.queryForm.startTime = createTM.value ? timeFormater(createTM.value[0]).format('YYYY-MM-DD') : ''
	state.queryForm.endTime = createTM.value ? timeFormater(createTM.value[1]).format('YYYY-MM-DD') : ''
	getDataList()
}

const resets = () => {
	createTM.value = ''
	state.queryForm = {
		startTime: '',
		endTime: '',
		status: '',
		username: '',
		projectId: 1,
		orgId: JSON.parse(sessionStorage.getItem('userInfo')).orgId
	}

	state.page = 1
	state.limit = 10

	state.dataListSelections = []

	getDataList()
}

const addOrUpdateRef = ref()
const addOrUpdateHandle = (id?: number, type?: string) => {
	addOrUpdateRef.value.init(id, type)
}
const handleMoveRef = ref()
const handleMove = () => {
	handleMoveRef.value.init()
}

const resetPassword = (id: number) => {
	ElMessageBox.confirm('确定重置密码?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			resetPasswordApi({ userId: id }).then(() => {
				ElMessage.success({
					message: '操作成功',
					duration: 500,
					onClose: () => {
						getDataList()
					}
				})
			})
		})
		.catch(() => {})
}

const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle, disableBatchHandle } = useCrud(state)
</script>
